/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-02-06
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-03-16
 * @Description: 
 */
import 'package:chat_client/config/api_config.dart';
import 'package:chat_client/config/socket_config.dart'
    show ConfirmEvents, NotifyEvents, NtifyContent;
import 'package:chat_client/enums/apply_enum.dart';
import 'package:chat_client/enums/chat_enum.dart';
import 'package:chat_client/models/apply_model.dart';
import 'package:chat_client/providers/application_provider.dart'
    show ApplicationProvider;
import 'package:chat_client/providers/contact_provider.dart'
    show ContactProvider;
import 'package:chat_client/repositories/auth_repository.dart';
import 'package:chat_client/repositories/contact_repository.dart';
import 'package:chat_client/services/contact_service.dart';
import 'package:chat_client/services/group_service.dart';
import 'package:chat_client/services/socket/socket_service.dart';
import 'package:chat_client/utils/notify/notify_enum.dart'
    show NotificationType;
import 'package:chat_client/utils/notify/notify_helper.dart';
import 'package:chat_client/utils/route_tools.dart' show generatePath;
import 'package:chat_client/router/router.dart' show navigatorKey;
import 'package:provider/provider.dart';

class NotifyService {
  // 单例模式
  NotifyService._internal() {
    // 初始化个人Id
    _userId = _authRepository.userSelfId;
  }
  static final NotifyService _instance = NotifyService._internal();
  static NotifyService get instance => _instance;

  final SocketService _socket = SocketService.instance;
  final ContactRepository contactRepository = ContactRepository.instance;
  final ContactService _contactService = ContactService.instance;
  final GroupService _groupService = GroupService.instance;
  final AuthRepository _authRepository = AuthRepository.instance;
  // 用户个人Id
  late final String _userId;

  register() {
    receivedFriendRequest();
    receivedGroupInvite();
  }

  // 自己发送：opponentId 是 receiver, 对伐发送 opponentId 是 sender

  /// 监听好友申请（一定是由对方操作引起）
  receivedFriendRequest() {
    receivedApply(data) async {
      // 1. 判断是否为我方发送检查sender
      final senderId = data['payload']['sender']['_id'];

      final notify = NtifyContent.fromJson(data);

      // 2. 我方发送
      if (senderId == _userId) {
        // 构建我方发送 opponentId为receiver._id !!!!!!!!

        final apply = Apply.fromJson(data['payload'], true);

        final Apply? localApply = contactRepository.getApply(apply.opponentId);
        // 更新状态
        contactRepository.updateApply(
          opponentId: localApply!.opponentId,
          status: apply.status,
        );

        // 对方接收
        if (apply.status == ApplyStatus.accepted.value) {
          // 2. 如果对方已接受
          // 顶部通知
          _notify(notify, NotificationType.friendRequest, null);
          _refreshContactList();
        }
      } else {
        // 构建非我方发送 opponentId为sender._id !!!!!!!!
        final apply = Apply.fromJson(data['payload'], false);

        //3. 对方发起的请求

        // 1. 储存
        await contactRepository.setApply(apply);
        // 2. 判断状态

        // 待处理申请
        if (apply.status == ApplyStatus.pending.value) {
          _notify(notify, NotificationType.friendRequest, null);
        } else if (apply.status == ApplyStatus.accepted.value) {
          // 已自动处理的申请
          await _contactService.getFriendInfo(apply.opponentId);

          _notify(
            notify,
            NotificationType.chat,
            generatePath(
              type: ConversationType.user.label,
              id: apply.opponentId,
            ),
          );

          // 刷申请列表和联系人列表UI
          _refreshContactList();
        }
      }

      // 3. 通知服务器确认我已收到通知并处理完毕
      _socket.emitEvent(eventName: ConfirmEvents.notify, data: notify.toMap());

      _refreshApplyList();
    }

    _socket.addEventListener(NotifyEvents.friendRequest, receivedApply);
  }

  receivedGroupInvite() {
    receivedInvite(data) async {
      // 1. 判断是否为我方创建或发起
      final ownerId = data['payload']['ownerId'];
      final groupId = data['payload']['groupId'];
      final notify = NtifyContent.fromJson(data);

      if (_userId == ownerId) {
        return;
      }
      // 2.拉取群聊
      await _groupService.getRemoteGroupById(groupId);
      _notify(
        notify,
        NotificationType.group,
        generatePath(
          type: ConversationType.group.label,
          id: groupId,
        ),
      );

      // 3. 通知服务器确认我已收到通知并处理完毕
      _socket.emitEvent(eventName: ConfirmEvents.notify, data: notify.toMap());

      _refreshApplyList();
    }

    _socket.addEventListener(NotifyEvents.publicGroupJoined, receivedInvite);
  }

  ///---------------------------------
  /// 刷新好友申请列表
  void _refreshApplyList() {
    final context = navigatorKey.currentContext;
    if (context != null) {
      context.read<ApplicationProvider>().refreshApplications();
    }
  }

  /// 刷新联系人列表
  void _refreshContactList() {
    final context = navigatorKey.currentContext;
    if (context != null) {
      context.read<ContactProvider>().refreshContacts();
    }
  }

  // 通知
  _notify(NtifyContent notify, NotificationType type, String? targetRoute) {
    NotifyHelper.notify(
      title: notify.title,
      content: notify.body,
      iconUrl: AppConfig.baseUrl + notify.icon,
      type: type,
      targetRoute: targetRoute,
    );
  }
}
